package com.example.demo.service;

import com.example.demo.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author corgi
 * @since 2022-09-04 19:48
 */
@Service
@Log4j2
@CacheConfig(cacheNames = "c1", keyGenerator = "myKeyGen")
public class UserService {

	/**
	 * cache key 是参数列表，默认方式
	 *
	 * @param id 用户ID
	 * @return user
	 */
	@Cacheable
	public User getUser(Integer id) {
		log.warn("进入数据库查询");
		User user = new User();
		user.setUserId(id);
		user.setUserMail("mashiro-e@qq.com");
		user.setUserName("Alejandra你好");
		return user;
	}

	/**
	 * 指定 cache key
	 *
	 * @param id   uid
	 * @param name uname
	 * @return u
	 */
	@Cacheable(key = "#id")
	public User getUser(Integer id, String name) {
		log.warn("进入数据库查询");
		User user = new User();
		user.setUserId(id);
		user.setUserMail("mashiro-e@qq.com");
		user.setUserName(name);
		return user;
	}

	/**
	 * 复杂 key, 指定一个key生成器
	 * keyGenerator: 实例名，类名首字母小写.
	 *
	 * @return u
	 */
	@Cacheable
	public User getUser(Integer id, String name, String email) {
		log.warn("进入数据库查询");
		User user = new User();
		user.setUserId(id);
		user.setUserMail(email);
		user.setUserName(name);
		return user;
	}

	/**
	 * 删除 同时删除缓存，删除缓存操作默认是在删除数据库之后
	 * 可以通过注解选项beforeInvocation配置
	 *
	 * @param id uid
	 * @return b
	 */
	@CacheEvict
	public boolean deleteUser(Integer id) {
		System.out.println("删除 id = " + id);
		return true;
	}

	@CachePut
	public boolean updateUser(Integer id) {
		System.out.println("更新 id = " + id);
		return true;
	}

}
